'use strict'

const app = getApp()
import { requestApi } from '../api.js'
import md5 from './md5.min'
import { dateFormat } from './dateFormat'

// uid 登录用户id
let uid = null

function getUid() {
  // 获取登录用户UID
  wx.getStorage({
    key: 'userinfo',
    success: (res) => {
      uid = res.data.uid
    },
  })
}

if (! uid) {
  getUid()
}

// 签名随机值
let nounce = Math.random().toString(32).substring(2) + Math.random().toString(32).substring(2)
// diu 当前应用唯一值
let diu = ''

try {
  diu = wx.getStorageSync('diu')
} catch (e) {
  //
}

if (!diu) {
  diu = md5(nounce + 'ofashion_mars')

  try {
    wx.setStorageSync('diu', diu)
  } catch (e) {
    //
  }
}

// 网络类型
let networkType = null

// 获取网络类型
wx.getNetworkType({
  success: function (res) {
    networkType = res.networkType
  },
  fail: function (res) { },
  complete: function (res) { },
})

function handleUpload(param) {
  let uploadParam = {
    current_page: {
      page_id: param.cur_page_id || null,
      page_resource_id: param.cur_page_resource_id || null,
      page_entrance_type: param.cur_page_entrance_type || 1,
      page_entrance_time: param.cur_page_entrance_time || null,
    },
    operation_info: {
      resource_area: param.opt_resource_area || null,
      resource_area_id: param.opt_resource_area_id || null,
      resource_area_index: param.opt_resource_area_index || null,
      resource_id: param.opt_resource_id || null,
      resource_type: param.opt_resource_type || null,
      write_server_timestamp: param.opt_time || null,
      phone: param.phone || null,
      countrycode: param.countrycode || null,
      share_type: param.share_type || null,
      share_link: param.share_link || null,
      share_title: param.share_title || null,
      share_subtitle: param.share_subtitle || null,
      resource_info: param.resource_info || null,
      extension: {
        order_pay_result_type: param.order_pay_result_type || null,
        order_pay_channel: param.order_pay_channel || null,
        trade_no: param.trade_no || null,
      }
    },
    impression_info: {
      page_id: param.impr_page_id || null,
      resource_area: param.impr_resource_area || null,
      resource_area_id: param.impr_resource_area_id || null,
      resource_area_index: param.impr_resource_area_index || null,
      resource_id: param.impr_resource_id || null,
      resource_type: param.impr_resource_type || null,
      resource_info: param.impr_resource_info || null,
      write_server_timestamp: param.impr_time || null,
    },
    refer: {
      current_page: {
        page_id: param.ref_page_id || null,
        page_resource_id: param.ref_page_resource_id || null,        
      },
      operation_info: {
        resource_area: param.ref_opt_resource_area || null,
        resource_area_id: param.ref_opt_resource_area_id || null,
        resource_area_index: param.ref_opt_resource_area_index || null,
        resource_id: param.ref_opt_resource_id || null,
        resource_type: param.ref_opt_resource_type || null,
        extension: {
          goods_color_name: param.goods_color || null,
          goods_spec_name: param.goods_spec || null,
          gid: param.gid || null,
        }
      },
      metadata: {
        log_type: param.log_type || null,
        write_sever_timestamp: param.ref_write_sever_timestamp || null,
      },
    },
    general: {
      source: '10',
      uid: uid || null,
      diu: diu || null,
      network_type: networkType || null,
    },
    metadata: {
      log_type: param.log_type || null,
      request_id: md5('10' + (new Date().getTime()) + 'diu' + param.cur_page_resource_id),
      write_server_timestamp: dateFormat('yyyy-MM-dd hh:mm:ss:S'),
    }
  }

  uploadParam['nounce'] = nounce
  uploadParam = nullFilter(uploadParam)

  function paramToArr(uploadParam) {
    let temp = ksort(uploadParam)
    let arr = []

    for (let p in temp) {
      if (typeof(temp[p]) == 'object') {
        temp[p] = paramToArr(temp[p])
      }

      if (temp.hasOwnProperty(p)) {
        arr.push(p + '=' + temp[p])
      }
    }

    return arr
  }

  let uploadArr = paramToArr(uploadParam)

  uploadParam['sign'] = md5(uploadArr.join('&') + 'ofashion' + nounce)

  app.request({
    url: requestApi.logUploadUrl,
    login: false,
    method: 'POST',
    data: uploadParam,
  }, (res) => {
    // console.log(res)
  }, (err) => {
    console.log(err)
  })
}

// 过滤值为null的字段
function nullFilter(data) {
  for(let i in data) {
    if (data[i] instanceof Object) {
      data[i] = nullFilter(data[i])
    }

    if (data[i] === null || data[i] == '' || data[i] == 'undefined' || data[i] == 'null' || JSON.stringify(data[i]) == '{}') {
      delete data[i]
    }
  }
  return data
}

function ksort(inputArr, sortFlag) {
  var tmp_arr = {},
    keys = [],
    sorter, i, k,
    strictForIn = false,
    populateArr = {}

  switch (sortFlag) {
    case 'SORT_STRING':
      // compare items as strings  
      sorter = function (a, b) {
        return this.strnatcmp(a, b)
      }

      break
    case 'SORT_LOCALE_STRING':
      // compare items as strings, original by the current locale (set with  i18n_loc_set_default() as of PHP6)  
      var loc = this.i18n_loc_get_default()
      sorter = this.php_js.i18nLocales[loc].sorting

      break
    case 'SORT_NUMERIC':
      // compare items numerically  
      sorter = function (a, b) {
        return ((a + 0) - (b + 0))
      }

      break
    // case 'SORT_REGULAR': // compare items normally (don't change types)  
    default:
      sorter = function (a, b) {
        var aFloat = parseFloat(a),
          bFloat = parseFloat(b),
          aNumeric = aFloat + '' === a,
          bNumeric = bFloat + '' === b

        if (aNumeric && bNumeric) {
          return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0
        } else if (aNumeric && !bNumeric) {
          return 1
        } else if (!aNumeric && bNumeric) {
          return -1
        }
        return a > b ? 1 : a < b ? -1 : 0
      }

      break
  }

  // Make a list of key names  
  for (k in inputArr) {
    if (inputArr.hasOwnProperty(k)) {
      keys.push(k)
    }
  }

  keys.sort(sorter)

  // BEGIN REDUNDANT  
  var php_js = php_js || {}
  php_js.ini = php_js.ini || {}

  // END REDUNDANT  
  strictForIn = php_js.ini['phpjs.strictForIn'] && php_js.ini['phpjs.strictForIn'].local_value && php_js
    .ini['phpjs.strictForIn'].local_value !== 'off'
  populateArr = strictForIn ? inputArr : populateArr

  // Rebuild array with sorted key names  
  for (i = 0; i < keys.length; i++) {
    k = keys[i]
    tmp_arr[k] = inputArr[k]

    if (strictForIn) {
      delete inputArr[k]
    }
  }

  for (i in tmp_arr) {
    if (tmp_arr.hasOwnProperty(i)) {
      populateArr[i] = tmp_arr[i]
    }
  }

  return strictForIn || populateArr
}

let logUpload = {
  handleUpload: handleUpload
}
export { logUpload }